//
//  ApiProvider.swift
//  test-ios
//
//  Created by wyz5204 on 2023/3/6.
//

import Foundation
import RxSwift
import SwiftyJSON
import Moya


class ApiProvider {
    static let shared = ApiProvider()
    
    
    func request(_ url : String ,_ request : BaseRequest<Any>) -> Observable<JSON>{
        return Observable.create { observable -> Disposable in
            
            var provider = MoyaProvider<RD>()
            
            provider.request(RD.Login) { result in
                
            }
            provider.rx.request(.Login).subscribe { event in
                switch event {
                case let .success(result) :
                    print(result)
                case let .failure(error) :
                    print(error)
                }
            }
            provider.rx.request(.Login).asObservable().map { event -> JSON in
                
                return JSON.init(parseJSON: "")
            }
            return Disposables.create()
        }
    }
    
    func request(_ url : RD) -> Observable<JSON>{
        return MoyaProvider<RD>().rx.request(url).asObservable().map { result -> JSON in
            print(result)
            return JSON.init(parseJSON: "")
        }
    }
}



enum RD {
    case Login
    case Register(phone:String , code:String)
    case getAppList
}

extension RD : TargetType {
    var baseURL: URL {
        switch self {
        case .getAppList :
            return URL(string: "https://open-test.rongdasoft.com/")!
        default :
            return URL(string: "https://go.apipost.cn/")!
        }
    }
    
    var path: String {
        switch self {
        case .Login :
            return "login"
        case .Register :
            return "register"
        case .getAppList :
            return "openplat/applet/getAppAppletList"
        default :
            return "empty error"
        }
    }
    
    var method: Moya.Method {
        return Method.post
    }
    
    var task: Task {
        switch self {
        case .Register(let phone,let code):
            print(phone , code)
            break
        default : break
        }
        var params: [String: Any] = [:]
        
        return .requestParameters(parameters: params, encoding: JSONEncoding.default)
    }
    
    var headers: [String : String]? {
        var headers: [String: String] = [:]
        switch self {
        case .Login:
            headers["Content-type"] = "application/json;charset=utf-8"
        default:
            headers["Content-type"] = "application/json;charset=utf-8"
        }
        return headers
    }

    
}
